<template>
    <div>
        <div class="card card-search">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="80px" size="small">
                <el-form-item label="时间" prop="customDate">
                    <el-radio-group v-model="queryParams.customDate" @change="changeCustomDate">
                        <el-radio-button :label="1">今天</el-radio-button>
                        <el-radio-button :label="2">昨天</el-radio-button>
                        <el-radio-button :label="3">近7天</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品spu" prop="spu">
                    <el-input v-model.trim="queryParams.spu" placeholder="请输入商品spu" clearable style="width: 200px" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="页面类型" prop="page_type">
                    <el-select v-model="queryParams.page_type" placeholder="请选择店铺" clearable style="width: 200px">
                        <el-option v-for="(dict, index) in pageTypeList" :key="index" :label="dict.label" :value="dict.label" />
                    </el-select>
                </el-form-item>
                <el-form-item label="日期" prop="date">
                    <el-date-picker
                        v-model="queryParams.date"
                        format="yyyy-MM-dd"
                        type="daterange"
                       
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        style="width: 240px"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button size="small" type="warning" plain icon="el-icon-download" :loading="download" :disabled="download" @click="handleExport">导出</el-button>
                </el-col>
                <right-toolbar size="small" :showSearch.sync="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table ref="sortTable" v-loading="loading" :data="tableData" row-key="id" border script @sort-change="handleSortChange">
                <el-table-column label="店铺" prop="shop_name" min-width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="页面类型" prop="page_type" min-width="100" show-overflow-tooltip v-if="showColumn('page_type')"></el-table-column>
                <el-table-column label="商品spu" prop="spu" min-width="100" show-overflow-tooltip v-if="showColumn('spu')"></el-table-column>
                <el-table-column label="运营" prop="admin_name" min-width="100" show-overflow-tooltip v-if="showColumn('admin_name')"></el-table-column>
                <el-table-column label="页面路径" prop="page_path" min-width="220" show-overflow-tooltip v-if="showColumn('page_path')">
                    <template slot-scope="scope">
                        <span v-if="!scope.row.product_url">{{ scope.row.page_path }}</span>
                        <el-link v-else type="primary" :underline="false" @click="toNewPage(scope.row)">{{ scope.row.page_path }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="访客" prop="total_visitors" width="100" sortable="custom" :sort-orders="['descending', 'ascending']" v-if="showColumn('total_visitors')"></el-table-column>
                <el-table-column label="访问" prop="total_sessions" width="100" sortable="custom" :sort-orders="['descending', 'ascending']" v-if="showColumn('total_sessions')"></el-table-column>
                <el-table-column label="加购物车" prop="total_carts" width="100" sortable="custom" :sort-orders="['descending', 'ascending']" v-if="showColumn('total_carts')"></el-table-column>
                <el-table-column
                    label="进入结算"
                    prop="total_checkouts"
                    width="100"
                    sortable="custom"
                    :sort-orders="['descending', 'ascending']"
                    v-if="showColumn('total_checkouts')"
                ></el-table-column>
                <el-table-column
                    label="成功访问"
                    prop="total_orders_placed"
                    min-width="100"
                    sortable="custom"
                    :sort-orders="['descending', 'ascending']"
                    show-overflow-tooltip
                    v-if="showColumn('total_orders_placed')"
                ></el-table-column>
                <el-table-column
                    label="转化率"
                    prop="total_conversion"
                    min-width="100"
                    sortable="custom"
                    :sort-orders="['descending', 'ascending']"
                    v-if="showColumn('total_conversion')"
                ></el-table-column>
                <el-table-column label="访问时长" prop="avg_duration" min-width="100" sortable="custom" :sort-orders="['descending', 'ascending']" v-if="showColumn('avg_duration')"></el-table-column>
                <el-table-column
                    label="跳出率"
                    prop="total_bounce_rate"
                    min-width="100"
                    sortable="custom"
                    :sort-orders="['descending', 'ascending']"
                    v-if="showColumn('total_bounce_rate')"
                ></el-table-column>
                <el-table-column
                    label="页面浏览量"
                    prop="total_pageviews"
                    min-width="120"
                    sortable="custom"
                    :sort-orders="['descending', 'ascending']"
                    show-overflow-tooltip
                    v-if="showColumn('total_pageviews')"
                ></el-table-column>
                <el-table-column label="创建时间" prop="create_time" min-width="160"></el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList" />
        </div>
    </div>
</template>
<script>
import { get_page_type, exportReportHistoryList } from '@/api/report'
import { getHistoryPerson } from '@/api/orderReportDataScreen'
import { parseTime } from '@/utils/quickadmin'
import { exportFile } from '@/utils/index'
export default {
    name: 'ReportVisitComponent',
    data() {
        return {
            // 遮罩层
            loading: true,
            download: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            tableData: [],
            pageTypeList: [],

            pageInfo: {
                page: 1,
                limit: 10,
            },
            // 查询参数
            queryParams: {
                spu: undefined,
                page_type: undefined,
                customDate: 2,
                date: [],
            },
            columns: [
                { label: '页面类型', prop: 'page_type', visible: true },
                { label: '商品spu', prop: 'spu', visible: true },
                { label: '运营', prop: 'admin_name', visible: true },
                { label: '页面路径', prop: 'page_path', visible: true },
                { label: '访客', prop: 'total_visitors', visible: true },
                { label: '访问', prop: 'total_sessions', visible: true },
                { label: '加购物车', prop: 'total_carts', visible: true },
                { label: '进入结算', prop: 'total_checkouts', visible: true },
                { label: '成功访问', prop: 'total_orders_placed', visible: true },
                { label: '转化率', prop: 'total_conversion', visible: true },
                { label: '访问时长', prop: 'avg_duration', visible: true },
                { label: '跳出率', prop: 'total_bounce_rate', visible: true },
                { label: '页面浏览量', prop: 'total_pageviews', visible: true },
                { label: '创建时间', prop: 'create_time', visible: true },
            ],
            detailDialog: {
                visible: false,
                data: {},
            },
        }
    },
    watch: {
        'queryParams.date': {
            handler(val) {
                if (val?.length == 2) {
                    this.queryParams.customDate = 0
                }
            },
            immediate: true,
            deep: true,
        },
    },
    async created() {
        this.loading = true
        try {
            const pageTypeResult = await get_page_type()
            this.pageTypeList = pageTypeResult?.data ?? []
        } catch (error) {
            this.loading = false
            console.log(error)
        }
        this.getList()
    },
    methods: {
        toNewPage(row) {
            const url = row.product_url
            if (url) {
                window.open(url, '_blank')
            }
        },
        changeCustomDate() {
            this.queryParams.date = []
            this.handleQuery()
        },
        showColumn(prop) {
            const data = this.columns.find(c => c.prop === prop)
            return data?.visible ?? true
        },
        resetSort() {
            this.queryParams.total_visitors = undefined
            this.queryParams.total_sessions = undefined
            this.queryParams.total_carts = undefined
            this.queryParams.total_checkouts = undefined
            this.queryParams.avg_duration = undefined
            this.queryParams.total_bounce_rate = undefined
            this.queryParams.total_conversion = undefined
            this.queryParams.total_orders_placed = undefined
            this.queryParams.total_pageviews = undefined
        },
        handleSortChange({ column, prop, order }) {
            this.resetSort()
            this.queryParams[prop] = order === 'descending' ? 'desc' : order === 'ascending' ? 'asc' : undefined
            this.getList()
        },
        showDetailDialog(row) {
            this.detailDialog.visible = true
            this.detailDialog.data = row
        },
        handleExport() {
            this.download = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.create_time?.length == 2) {
                qyparams.create_time = [parseTime(qyparams.create_time[0], 'y-m-d'), parseTime(qyparams.create_time[1], 'y-m-d')]
            }
            exportReportHistoryList(qyparams)
                .then(res => {
                    exportFile(res, () => {
                        this.download = false
                    })
                })
                .catch(err => {
                    console.log(err)
                    this.download = false
                })
        },
        handleClick() {
            this.getList()
        },

        //列表
        getList() {
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.create_time?.length == 2) {
                qyparams.create_time = [parseTime(qyparams.create_time[0], 'y-m-d'), parseTime(qyparams.create_time[1], 'y-m-d')]
            }
            getHistoryPerson(qyparams)
                .then(response => {
                    this.tableData = response.data.list
                    this.tableData.map(item => {
                        item.product_images = item.product_images?.replaceAll('\\', '')
                        return { ...item }
                    })
                    this.total = response.data.total
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')
            this.resetSort()
            this.$refs.sortTable.clearSort()
            this.handleQuery()
        },

        //更新排序
        updateSort() {
            this.$confirm(`预计等待一分钟`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.baseRequest_updateSort({})
                })
                .catch(err => {})
        },
        baseRequest_updateSort({}) {
            this.request
                .post('/product/ProductInventory/updateSort', {})
                .then(response => {
                    console.log('response', response)

                    if (response.code == 200) {
                        this.$message.success('操作成功')
                    }
                    console.log('test', 13)

                    this.getList()
                })
                .finally(() => {})
        },
    },
}
</script>
<style lang="scss" scoped></style>
